package net.sureon.web.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.app.AppContext;
import net.sureon.biz.GroupBO;
import net.sureon.biz.GroupMgr;
import net.sureon.biz.UserBO;
import net.sureon.biz.UserMgr;
import net.sureon.common.exception.SureonException;
import net.sureon.common.security.Action;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class StaffList implements Controller {
	private String successView;
	private UserMgr userMgr;
	private GroupMgr groupMgr;

	/**
	 * @return the successView
	 */
	public String getSuccessView() {
		return successView;
	}

	/**
	 * @param successView
	 *            the successView to set
	 */
	public void setSuccessView(String successView) {
		this.successView = successView;
	}

	/**
	 * @return the userMgr
	 */
	public UserMgr getUserMgr() {
		return userMgr;
	}

	/**
	 * @param userMgr
	 *            the userMgr to set
	 */
	public void setUserMgr(UserMgr userMgr) {
		this.userMgr = userMgr;
	}

	/**
	 * @return the groupMgr
	 */
	public GroupMgr getGroupMgr() {
		return groupMgr;
	}

	/**
	 * @param groupMgr the groupMgr to set
	 */
	public void setGroupMgr(GroupMgr groupMgr) {
		this.groupMgr = groupMgr;
	}

	private static final String ATTRI_USERS = "users";
	private static final String PARAM_VIEW = "view";
	private static final String PARAM_VAL_TEAM = "team";

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		List<UserBO> users = null;
		if (PARAM_VAL_TEAM.equals(request.getParameter(PARAM_VIEW))) {
			if (Action.WriteGroup.probeAccess(userMgr.getUser(AppContext.getCompanyID(), AppContext.getUserID()))) {
				ModelAndView view = new ModelAndView(getSuccessView(), result);
				users = new ArrayList<UserBO>();
				List<Long> userIDs = userMgr.getChildUsersWithConfiguredLevel(AppContext.getCompanyID(), AppContext.getUserID());
				for(Long userID : userIDs){
					users.add(userMgr.getUser(AppContext.getCompanyID(), userID));
				}
			}
		} else {
			users = getCompanyUsers();
		}
		result.put(ATTRI_USERS, users);
		result.put(PARAM_VIEW, request.getParameter(PARAM_VIEW));
		ModelAndView view = new ModelAndView(getSuccessView(), result);
		return view;
	}

	private List<UserBO> getCompanyUsers() throws SureonException {
		return userMgr.getUserByCompanyID(AppContext.getCompanyID(), 0, 1000);
	}
}
